package com.leo.erp.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.erp.dao.AccountDao;
import com.leo.erp.dao.AccountHeadMapper;
import com.leo.erp.dao.AccountItemMapper;
import com.leo.erp.dao.AccountMapper;
import com.leo.erp.dao.DepotHeadMapper;
import com.leo.erp.dto.AccountExecution;
import com.leo.erp.entity.Account;
import com.leo.erp.entity.AccountHead;
import com.leo.erp.entity.AccountItem;
import com.leo.erp.entity.AccountVo4InOutList;
import com.leo.erp.entity.DepotHead;
import com.leo.erp.entity.User;
import com.leo.erp.enums.AccountStateEnum;
import com.leo.erp.service.AccountService;
import com.leo.erp.service.LogService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.PageCalculator;
import com.leo.erp.util.StringUtil;
import com.leo.erp.util.Tools;

@Service
public class AccountServiceImpl implements AccountService{
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private DepotHeadMapper depotHeadMapper;
	@Autowired
	private AccountHeadMapper accountHeadMapper;
	@Autowired
	private AccountItemMapper accountItemMapper;
	@Autowired
	private LogService logService;
	@Autowired
	private AccountDao accountDao;

	@Override
	public AccountExecution getStatistics() {
		AccountExecution ae = new AccountExecution();
		QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("deleteFlag", "1");
		
		try {
			List<Account> list = accountMapper.selectList(queryWrapper);
			String timeStr = Tools.getCurrentMonth();
			BigDecimal allMonthAmount = BigDecimal.ZERO;
            BigDecimal allCurrentAmount = BigDecimal.ZERO;
            if (null != list && null != timeStr) {
                for (Account a : list) {
                	BigDecimal initialAmount = BigDecimal.valueOf(a.getInitialAmount());
                    BigDecimal monthAmount = getAccountSum(a.getAccountId(), timeStr, "month").add(getAccountSumByHead(a.getAccountId(), timeStr, "month"))
                            .add(getAccountSumByDetail(a.getAccountId(), timeStr, "month")).add(getManyAccountSum(a.getAccountId(), timeStr, "month"));
                    BigDecimal currentAmount = getAccountSum(a.getAccountId(), "", "month").add(getAccountSumByHead(a.getAccountId(), "", "month"))
                            .add(getAccountSumByDetail(a.getAccountId(), "", "month")).add(getManyAccountSum(a.getAccountId(), "", "month")).add(initialAmount);
                    allMonthAmount = allMonthAmount.add(monthAmount);
                    allCurrentAmount = allCurrentAmount.add(currentAmount);
                }
            }
            ae.setState(AccountStateEnum.SUCCESS.getState());
            Map<String, Object> map = new HashMap<>();
            map.put("allCurrentAmount", priceFormat(allCurrentAmount));//当前总金额
            map.put("allMonthAmount", priceFormat(allMonthAmount)); //本月发生额
			ae.setAccountMap(map);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ae;
	}

	/**
     * 价格格式化
     * @param price
     * @return
     */
	private Object priceFormat(BigDecimal price) {
		String priceFmt = "0";
        DecimalFormat df = new DecimalFormat(".##");
        if ((price.compareTo(BigDecimal.ZERO)) != 0) {
            priceFmt = df.format(price);
        }
        return priceFmt;
	}

	/**
     * 单个账户的金额求和-多账户的明细合计
     *
     * @param id
     * @return
     */
	private BigDecimal getManyAccountSum(int accountId, String timeStr, String type) {
		BigDecimal accountSum = BigDecimal.ZERO;
        try {
        	QueryWrapper<DepotHead> queryWrapper = new QueryWrapper<>();
            if (!timeStr.equals("")) {
                Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if (type.equals("month")) {
                	queryWrapper.like("accountIdList", "%" + accountId + "%");
                	queryWrapper.ge("operTime", bTime).le("operTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                } else if (type.equals("date")) {
                	queryWrapper.like("accountIdList", "%" + accountId + "%");
                	queryWrapper.le("operTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }
            } else {
            	queryWrapper.like("accountIdList", "%" + accountId + "%");
            	queryWrapper.ne("deleteFlag", "1");
            }
            List<DepotHead> dataList = null;
            try{
                dataList = depotHeadMapper.selectList(queryWrapper);
            }catch(Exception e){
                e.printStackTrace();
            }
            if (dataList != null) {
                for (DepotHead depotHead : dataList) {
                    String accountIdList = depotHead.getAccountIdList();
                    String accountMoneyList = depotHead.getAccountMoneyList();
                    if(StringUtil.isNotEmpty(accountIdList) && StringUtil.isNotEmpty(accountMoneyList)) {
                        accountIdList = accountIdList.replace("[", "").replace("]", "").replace("\"", "");
                        accountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replace("\"", "");
                        String[] aList = accountIdList.split(",");
                        String[] amList = accountMoneyList.split(",");
                        for (int i = 0; i < aList.length; i++) {
                            if (aList[i].toString().equals(accountId)) {
                                if(amList != null && amList.length > 0) {
                                    accountSum = accountSum.add(new BigDecimal(amList[i]));
                                }
                            }
                        }
                    }
                }
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return accountSum;
	}

	/**
     * 单个账户的金额求和-收款、付款、转账、收预付款的单据明细的合计
     *
     * @param id
     * @return
     */
	private BigDecimal getAccountSumByDetail(int accountId, String timeStr, String type) {
		BigDecimal accountSum =BigDecimal.ZERO ;
        try {
            QueryWrapper<AccountHead> queryWrapper = new QueryWrapper<>();
            if (!timeStr.equals("")) {
                Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if (type.equals("month")) {
                	queryWrapper.ge("billTime", bTime).le("billTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                } else if (type.equals("date")) {
                	queryWrapper.le("billTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }
            }
            List<AccountHead> dataList = null;
            try{
                dataList = accountHeadMapper.selectList(queryWrapper);
            }catch(GlobalRuntimeException e){
                e.printStackTrace();
            }
            if (dataList != null) {
                String ids = "";
                for (AccountHead accountHead : dataList) {
                    ids = ids + accountHead.getAccountHeadId() + ",";
                }
                if (!ids.equals("")) {
                    ids = ids.substring(0, ids.length() - 1);
                }
                QueryWrapper<AccountItem> queryItem = new QueryWrapper<>();
                if (!ids.equals("")) {
                    List<Long> idList = StringUtil.strToLongList(ids);
                    queryItem.eq("accountId", accountId);
                    queryItem.in("headerId", idList);
                    queryItem.ne("deleteFlag", "1");
                    List<AccountItem> dataListOne = accountItemMapper.selectList(queryItem);
                    if (dataListOne != null) {
                        for (AccountItem accountItem : dataListOne) {
                            if(accountItem.getEachAmount() > 0) {
                            	BigDecimal decimalD = BigDecimal.valueOf(accountItem.getEachAmount());
                                accountSum = accountSum.add(decimalD);
                            }
                        }
                    }
                }
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        } catch (GlobalRuntimeException e) {
            e.printStackTrace();
        }
        return accountSum;
	}

	/**
     * 单个账户的金额求和-收入、支出、转账的单据表头的合计
     *
     * @param id
     * @return
     */
	private BigDecimal getAccountSumByHead(int accountId, String timeStr, String type) {
		BigDecimal accountSum = BigDecimal.ZERO;
        try {
            QueryWrapper<AccountHead> queryWrapper = new QueryWrapper<>();
            if (!timeStr.equals("")) {
                Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if (type.equals("month")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.ge("billTime", bTime).le("billTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                } else if (type.equals("date")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.le("billTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }
            } else {
            	queryWrapper.eq("accountId", accountId);
            	queryWrapper.ne("deleteFlag", "1");
            }
            List<AccountHead> dataList = null;
            try{
                dataList = accountHeadMapper.selectList(queryWrapper);
            }catch(GlobalRuntimeException e){
                e.printStackTrace();
            }
            if (dataList != null) {
                for (AccountHead accountHead : dataList) {
                    if(accountHead.getChangeAmount() > 0) {
                    	BigDecimal decimalD = BigDecimal.valueOf(accountHead.getChangeAmount());
                        accountSum = accountSum.add(decimalD);
                    }
                }
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return accountSum;
	}

	/**
     * 单个账户的金额求和-入库和出库
     *
     * @param id
     * @return
     */
	private BigDecimal getAccountSum(int accountId, String timeStr, String type) {
		BigDecimal accountSum = BigDecimal.ZERO;
        try {
            QueryWrapper<DepotHead> queryWrapper = new QueryWrapper<>();
            if (!timeStr.equals("")) {
                Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if (type.equals("month")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.ne("payType", "预付款");
                	queryWrapper.ge("operTime", bTime).le("operTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                } else if (type.equals("date")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.ne("payType", "预付款");
                	queryWrapper.le("operTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }
            } else {
            	queryWrapper.eq("accountId", accountId);
            	queryWrapper.ne("payType", "预付款");
            	queryWrapper.ne("deleteFlag", "1");
            }
            List<DepotHead> dataList=null;
            try{
                dataList = depotHeadMapper.selectList(queryWrapper);
            }catch(Exception e){
                e.printStackTrace();
            }
            if (dataList != null) {
                for (DepotHead depotHead : dataList) {
                    if(depotHead.getChangeAmount() > 0) {
                    	BigDecimal decimalD = BigDecimal.valueOf(depotHead.getChangeAmount());
                        accountSum = accountSum .add(decimalD) ;
                    }
                }
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return accountSum;
	}

	@Override
	public AccountExecution checkIsNameExist(int id, String name) {
		AccountExecution ae = new AccountExecution();
		QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("accountId", id);
		queryWrapper.eq("accountName", name);
		queryWrapper.ne("deleteFlag", "1");
		try {
			List<Account> list = accountMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				ae.setState(AccountStateEnum.SUCCESS.getState());
			}else {
				ae.setState(AccountStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ae;
	}

	@Override
	public AccountExecution insertAccount(String beanJson, HttpServletRequest request) throws GlobalRuntimeException {
		AccountExecution ae = new AccountExecution();
		Account account = JSONObject.parseObject(beanJson, Account.class);
		//account.setIsDefault(1);
		//session
		User user = (User) request.getSession().getAttribute("user");
		account.setTenantId(user.getUserId());
		account.setCurrentAmount(account.getInitialAmount());
		try {
			int effectedNum = accountMapper.insert(account);
			if(effectedNum > 0) {
				logService.insertLog("帐户", "新增" + account.getAccountName(), request);
				ae.setState(AccountStateEnum.SUCCESS.getState());
			}else {
				ae.setState(AccountStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ae;
	}

	@Override
	public AccountExecution getAccount() {
		AccountExecution ae = new AccountExecution();
		QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("deleteFlag", "1");
		try {
			List<Account> list = accountMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				ae.setState(AccountStateEnum.SUCCESS.getState());
				ae.setAccountList(list);
			}else {
				ae.setState(AccountStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ae;
	}

	/**
	 * 正常删除，要考虑数据完整性，进行完整性校验
	 */
	@Override
	@Transactional
	public AccountExecution batchDeleteAccountByIdsNormal(String ids) {
		AccountExecution ae = new AccountExecution();
		/**
         * 校验：
         * 1、财务主表	tb_account_head
         * 2、财务子表	tb_account_item
         * 3、单据主表	tb_depot_head
         * 是否有相关数据
         * */
		if(StringUtil.isEmpty(ids)) {
			ae.setState(AccountStateEnum.OFFLINE.getState());
			return ae;
		}
		
		List<Long> idList = StringUtil.strToLongList(ids);//转换成数组
		
		/**
         * 校验财务主表	tb_account_head
         * */
		try {
			QueryWrapper<AccountHead> queryAccountHead = new QueryWrapper<>();
			queryAccountHead.in("accountId", idList);
			List<AccountHead> accountHeadList = accountHeadMapper.selectList(queryAccountHead);
			if(accountHeadList.size() > 0) {
				//有数据,可以执行强制删除
				ae.setState(AccountStateEnum.DELETE.getState());
				return ae;
				//throw new GlobalRuntimeException("检测到存在依赖数据，是否强制删除？");
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
         * 校验财务子表	tb_account_item
         * */
		try {
			QueryWrapper<AccountItem> queryAccountItem = new QueryWrapper<>();
			queryAccountItem.in("accountId", idList);
			List<AccountItem> accountItemList = accountItemMapper.selectList(queryAccountItem);
			if(accountItemList.size() > 0) {
				//有数据,可以执行强制删除
				ae.setState(AccountStateEnum.DELETE.getState());
				return ae;
			}else {
				
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
         * 校验单据主表	tb_depot_head
         **/
		try {
			QueryWrapper<DepotHead> queryDepotHead = new QueryWrapper<>();
			queryDepotHead.in("accountId", idList);
			List<DepotHead> depotHeadList = depotHeadMapper.selectList(queryDepotHead);
			if(depotHeadList.size() > 0) {
				ae.setState(AccountStateEnum.DELETE.getState());
				return ae;
				//throw new GlobalRuntimeException("检测到存在依赖数据，是否强制删除？");
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
         * 校验通过执行删除操作
         * */
		int effectedNum = batchDeleteAccountByIds(ids);
		if(effectedNum > 0) {
			ae.setState(AccountStateEnum.SUCCESS.getState());
		}else {
			ae.setState(AccountStateEnum.OFFLINE.getState());
		}
		
		return ae;
	}
	
	@Transactional
	@Override
	public int batchDeleteAccountByIds(String ids) {
		StringBuffer sb = new StringBuffer();
		List<Long> idList = StringUtil.strToLongList(ids);
		QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("accountId", idList);
		List<Account> list = accountMapper.selectList(queryWrapper);
		for(Account account : list) {
			sb.append("[").append(account.getAccountName()).append("]");
		}
		logService.insertLog("帐户", sb.toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
		//session
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		User user = (User) request.getSession().getAttribute("user");
		int effectedNum = 0;
		try {
			Account account = new Account();
			account.setDeleteFlag("1");
			account.setTenantId(user.getUserId());
			UpdateWrapper<Account> updateWrapper = new UpdateWrapper<>();
			updateWrapper.in("accountId", idList);
			
			effectedNum = accountMapper.update(account, updateWrapper);
			
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return effectedNum;
	}

	@Override
	public AccountExecution updateAmountIsDefault(int isDefault, int accountId) {
		AccountExecution ae = new AccountExecution();
		Account account = accountMapper.selectById(accountId);
		account.setIsDefault(isDefault);
		
		try {
			int effectedNum = accountMapper.updateById(account);
			if(effectedNum > 0) {
				ae.setState(AccountStateEnum.SUCCESS.getState());
			}else {
				ae.setState(AccountStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ae;
	}

	@Override
	public AccountExecution updateAccount(String beanJson, int accountId, HttpServletRequest request) {
		AccountExecution ae = new AccountExecution();
		Account account = JSONObject.parseObject(beanJson, Account.class);
		//session
		User user = (User) request.getSession().getAttribute("user");
		account.setTenantId(user.getUserId());
		account.setAccountId(accountId);
		account.setCurrentAmount(account.getInitialAmount());
		try {
			int effectedNum = accountMapper.updateById(account);
			if(effectedNum > 0) {
				logService.insertLog("帐户", "修改:" + account.getAccountName().toString(), request);
				ae.setState(AccountStateEnum.SUCCESS.getState());
			}else {
				ae.setState(AccountStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return ae;
	}

	@Override
	public AccountExecution getList(String name, String serialNo, String remark, int currentPage, int pageSize) {
		AccountExecution ae = new AccountExecution();
		QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
		
		//判断
		if(name != null && name != "") {
			queryWrapper.like("accountName", name);
		}
		if(serialNo != null && serialNo != "") {
			queryWrapper.like("serialNo", serialNo);
		}
		if(remark != null && remark != "") {
			queryWrapper.like("remark", remark);
		}
		queryWrapper.ne("deleteFlag", "1");
		Page<Account> page = new Page<>(currentPage, pageSize);//分页查询
		IPage<Map<String, Object>> iPage = accountMapper.selectMapsPage(page, queryWrapper);
		
		List<Map<String, Object>> accountPageList = new ArrayList<>();
		String timeStr = Tools.getCurrentMonth();
		if(null != iPage.getRecords() && null != timeStr) {
			for(Map<String, Object> ac : iPage.getRecords()) {
				Double thisMonthAmount = getAccountSum(ac.get("accountId"), timeStr, "month") + getAccountSumByHead(ac.get("accountId"), timeStr, "month") + getAccountSumByDetail(ac.get("accountId"), timeStr, "month") + getManyAccountSum(ac.get("accountId"), timeStr, "month");
				Double currentAmount = getAccountSum(ac.get("accountId"), timeStr, "month") + getAccountSumByHead(ac.get("accountId"), timeStr, "month") + getAccountSumByDetail(ac.get("accountId"), timeStr, "month") + getManyAccountSum(ac.get("accountId"), timeStr, "month") + Double.valueOf(ac.get("initialAmount").toString());
				ac.put("thisMonthAmount", thisMonthAmount);
				ac.put("currentAmount", currentAmount);
				accountPageList.add(ac);
			}
		}
		ae.setAccountPageList(accountPageList);
		ae.setPages(page.getPages());//总页数
		ae.setTotal(iPage.getTotal());//总记录数
		return ae;
	}
	
	/**
	 * 单个账户的金额求和-多账户的明细合计
	 * @param accountId
	 * @param timeStr
	 * @param type
	 * @return
	 */
	@Override
	public Double getManyAccountSum(Object accountId, String timeStr, String type) {
		Double accountSum = 0.0;
		try {
			QueryWrapper<DepotHead> queryWrapper = new QueryWrapper<>();
			if(!timeStr.equals("")) {
				Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if (type.equals("month")) {
                	queryWrapper.like("accountId", accountId);
                	queryWrapper.ge("operTime", bTime);
                	queryWrapper.le("operTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                }else if(type.equals("date")) {
                	queryWrapper.like("accountId", accountId);
                	queryWrapper.le("operTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }
			}else {
				queryWrapper.like("accountId", accountId);
            	queryWrapper.ne("deleteFlag", "1");
			}
			List<DepotHead> dataList = null;
			try {
				dataList = depotHeadMapper.selectList(queryWrapper);
			} catch (GlobalRuntimeException e) {
				e.printStackTrace();
			}
			if(dataList != null) {
				for(DepotHead depotHead : dataList) {
					String accountIdList = depotHead.getAccountIdList();
					String accountMoneyList = depotHead.getAccountMoneyList();
					if(StringUtil.isNotEmpty(accountIdList) && StringUtil.isNotEmpty(accountMoneyList)) {
                        accountIdList = accountIdList.replace("[", "").replace("]", "").replace("\"", "");
                        accountMoneyList = accountMoneyList.replace("[", "").replace("]", "").replace("\"", "");
                        String[] aList = accountIdList.split(",");
                        String[] amList = accountMoneyList.split(",");
                        for (int i = 0; i < aList.length; i++) {
                            if (aList[i].toString().equals(accountId.toString())) {
                                if(amList != null && amList.length > 0) {
                                    accountSum = accountSum + Double.valueOf(amList[i]);
                                }
                            }
                        }
                    }
				}
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return accountSum;
	}

	/**
	 * 单个账户的金额求和-收款、付款、转账、收预付款的单据明细的合计
	 * @param accountId
	 * @param timeStr
	 * @param type
	 * @return
	 */
	@Override
	public Double getAccountSumByDetail(Object accountId, String timeStr, String type) {
		Double accountSum = 0.0;
		try {
			QueryWrapper<AccountHead> queryWrapper = new QueryWrapper<>();
			if(!timeStr.equals("")) {
				Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if(type.equals("month")) {
                	queryWrapper.ge("billTime", bTime);
                	queryWrapper.le("billTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                }else if(type.equals("date")) {
                	queryWrapper.le("billTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }
			}
			List<AccountHead> dataList = null;
			try {
				dataList = accountHeadMapper.selectList(queryWrapper);
			} catch (GlobalRuntimeException e) {
				e.printStackTrace();
			}
			if(dataList != null) {
				String ids = "";
				for(AccountHead accountHead : dataList) {
					ids = ids + accountHead.getAccountHeadId() + ",";
				}
				if(!ids.equals("")) {
					ids = ids.substring(0, ids.length() - 1);
				}
				QueryWrapper<AccountItem> queryAccountItem = new QueryWrapper<>();
				if(!ids.equals("")) {
					List<Long> idList = StringUtil.strToLongList(ids);
					queryAccountItem.eq("accountId", accountId);
					queryAccountItem.in("headerId", idList);
					queryAccountItem.ne("deleteFlag", "1");
					List<AccountItem> dataListOne = accountItemMapper.selectList(queryAccountItem);
					if(dataListOne != null) {
						for(AccountItem accountItem : dataListOne) {
							if(accountItem.getEachAmount() != 0) {
								accountSum = accountSum + accountItem.getEachAmount();
							}
						}
					}
				}
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return accountSum;
	}

	/**
	 * 单个账户的金额求和-收入、支出、转账的单据表头的合计
	 * @param accountId
	 * @param timeStr
	 * @param type
	 * @return
	 */
	@Override
	public Double getAccountSumByHead(Object accountId, String timeStr, String type) {
		Double accountSum = 0.0;
		try {
			QueryWrapper<AccountHead> queryWrapper = new QueryWrapper<>();
			if(!timeStr.equals("")) {
				Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if (type.equals("month")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.ge("billTime", bTime);
                	queryWrapper.le("billTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                }else if(type.equals("date")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.le("billTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }
			} else {
            	queryWrapper.eq("accountId", accountId);
            	queryWrapper.ne("deleteFlag", "1");
            }
            List<AccountHead> dataList = null;
            try {
				dataList = accountHeadMapper.selectList(queryWrapper);
			} catch (GlobalRuntimeException e) {
				e.printStackTrace();
			}
            if(dataList != null) {
            	for(AccountHead accountHead : dataList) {
            		if(accountHead.getChangeAmount() != 0) {
            			accountSum = accountSum + accountHead.getChangeAmount();
            		}
            	}
            }
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return accountSum;
	}

	/**
	 * 单个账户的金额求和-入库和出库
	 * @param accountId
	 * @param timeStr
	 * @param type
	 * @return
	 */
	@Override
	public Double getAccountSum(Object accountId, String timeStr, String type) {
		Double accountSum = 0.0;
		try {
			QueryWrapper<DepotHead> queryWrapper = new QueryWrapper<>();
			if(!timeStr.equals("")) {
				Date bTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                Date eTime = StringUtil.getDateByString(timeStr + "-31 00:00:00", null);
                Date mTime = StringUtil.getDateByString(timeStr + "-01 00:00:00", null);
                if(type.equals("month")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.ne("payType", "预付款");
                	queryWrapper.ge("operTime", bTime);
                	queryWrapper.le("operTime", eTime);
                	queryWrapper.ne("deleteFlag", "1");
                }else if(type.equals("date")) {
                	queryWrapper.eq("accountId", accountId);
                	queryWrapper.ne("payType", "预付款");
                	queryWrapper.le("operTime", mTime);
                	queryWrapper.ne("deleteFlag", "1");
                }             
			} else {
            	queryWrapper.eq("accountId", accountId);
            	queryWrapper.ne("payType", "预付款");
            	queryWrapper.ne("deleteFlag", "1");
            }
            List<DepotHead> dataList = null;
            try {
				dataList = depotHeadMapper.selectList(queryWrapper);
			} catch (GlobalRuntimeException e) {
				e.printStackTrace();
			}
            if(dataList != null) {
            	for(DepotHead depotHead : dataList) {
            		if(depotHead.getChangeAmount() != 0) {
            			accountSum = accountSum + depotHead.getChangeAmount();
            		}
            	}
            }
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return accountSum;
	}

	@Override
	public List<AccountVo4InOutList> findAccountInOutList(int accountId, Integer currentPage, Integer pageSize) {
		List<AccountVo4InOutList> list=null;
		currentPage = PageCalculator.calculateRowIndex(currentPage, pageSize);
		try {
			list = accountDao.findAccountInOutList(accountId, currentPage, pageSize);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return list;
	}
	
	
}
